package com.czkevin.cif.commands.main;

import com.czkevin.cif.CIFItemInstance;
import com.czkevin.cif.CIFSubCommand;
import com.czkevin.cif.CustomItemFramework;
import com.czkevin.cif.EnchantableItem;
import com.czkevin.cif.commands.CIFMainCommand;
import com.czkevin.cif.enchantments.EnchantmentRegister;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class EnchantmentCommand implements CIFSubCommand {
  @Override
  public String getCommandName() {
    return "enchantment";
  }

  @Override
  public String getHelpParameters() {
    return "<name> [level]/remove";
  }

  @Override
  public String getHelpText() {
    return "Set enchantment. ";
  }

  @Override
  public void execute(CommandSender sender, String[] args) {
    if(!sender.hasPermission(CIFMainCommand.PERMISSION)) {
      sender.sendMessage("\u00a7cNo permissions! ");
      return;
    }
    if(!Player.class.isAssignableFrom(sender.getClass())) {
      return;
    }
    Player player = (Player) sender;
    ItemStack hand = player.getInventory().getItemInMainHand();
    CIFItemInstance instance = CustomItemFramework.getCIFDataFromItem(hand);
    if(instance == null || !EnchantableItem.class.isAssignableFrom(instance.type.getClass())) {
      sender.sendMessage("\u00a7cNot enchantable! ");
      return;
    }
    boolean add;
    if(args.length > 1 && "remove".equalsIgnoreCase(args[1])) {
      ((EnchantableItem) instance.type).removeEnchantment(instance, EnchantmentRegister.get(args[0]));
      add = false;
    } else {
      ((EnchantableItem) instance.type).setEnchantment(instance, EnchantmentRegister.get(args[0]),
          args.length > 1 ? Integer.parseInt(args[1]) : 1);
      add = true;
    }

    hand = instance.type.generateItemStack(instance, false);
    player.getInventory().setItemInMainHand(hand);

    player.sendMessage(String.format("\u00a7aEnchantment %s! ", add ? "added" : "removed"));

  }

  @Override
  public List<String> tabComplete(String[] args) {
    if(args.length == 1) {
      return EnchantmentRegister.listTypes();
    } else if (args.length == 2) {
      return Arrays.asList("1", "2", "3", "4", "5", "remove");
    } else {
      return Collections.emptyList();
    }
  }
}
